import plugin from '../../lib/plugins/plugin.js'
import fs from 'fs'
import YAML from "yaml"
import path from "path"
import puppeteer from '../../lib/puppeteer/puppeteer.js'
import common from "../../lib/common/common.js"
import schedule from 'node-schedule'

let toudowns = new Map()
let min = 10

let fuckpath = 'data/fuck'
if (!fs.existsSync(fuckpath)) {
    fs.mkdirSync(fuckpath)
}
let file = `${fuckpath}/config.yaml`
if (!fs.existsSync(file)) {
    fs.writeFileSync(file, `{}`)
}
let ml = process.cwd()
let avatorurl = `https://q1.qlogo.cn/g?b=qq&s=160&nk=`
export class fuck extends plugin {
  constructor () {
    super({
      name: '银趴',
      dsc: '群银趴',
      event: 'message',
      priority: 5000,
      rule: [
        {
          reg: '^#?(透|草|日)群友(.*)$',
          fnc: 'fuck'
        },
        {
          reg: '^#?(透|草|日)群主$',
          fnc: 'fuckowner'
        },
        {
          reg: '^#?(透|草|日)管理$',
          fnc: 'fuckadmin'
        },
		{
          reg: '^#?(挨透|被透|注射|注入|被草|银趴)查询(.*)$',
          fnc: 'toucha'
        },
		{
          reg: '^#?(查看)?(今日)?(挨透|被透|注射|注入|被草|银趴)(榜|榜单|排行|排行榜|排名)$',
          fnc: 'toubang'
        },
		{
          reg: '^#(关闭|开启)银趴$|#银趴冷却(.*)$',
          fnc: 'fuckset'
        },
		{
          reg: '^#银趴帮助$',
          fnc: 'fuckhelp'
        }
      ]
    })
  }
 

  async fuckhelp(e) {
    await e.reply(`管理&群主指令：\n#(关闭|开启)银趴  #银趴冷却30秒\n通用指令：\n透群主  透管理  透群友(可以@某人或携带qq号)\n银趴排名  银趴查询(可以@某人或携带qq号)`)
	return true
  }

  async fuckset(e) {
	if (!e.isGroup && !e.isMaster && !e.member.is_admin && !e.member.is_owner) {
		logger.info(`无权限`)
		return
	}
    let groupId = e.group_id
	let data = await loadfile(groupId)
	
	if (e.msg == "#开启银趴") {
	    data[groupId].fuck = true
		await fs.writeFileSync(file, YAML.stringify(data))
	    await e.reply(`[${groupId}]已开启银趴`,false,{ recallMsg: 10 })
	}
	if (e.msg == "#关闭银趴") {
	    data[groupId].fuck = false
		await fs.writeFileSync(file, YAML.stringify(data))
		await e.reply(`[${groupId}]已关闭银趴`,false,{ recallMsg: 10 })
	}	
    if (e.msg.includes("#银趴冷却")) {
		let key = e.msg.replace(/#?银趴冷却|设置|秒|s|S/g, '').trim()
		if (isNaN(key)) return e.reply('请键入正确的数字，单位秒')
		if (key < 0) return e.reply('银趴冷却最少设置0秒')
		data[groupId].cd = Number(key)
		await fs.writeFileSync(file, YAML.stringify(data))
		await e.reply(`[${groupId}]银趴冷却已设置 ${key} 秒`,false,{ recallMsg: 10 })
	}			
  }  
		
		
  async fuck(e) {
    if (!e.isGroup) {
        await e.reply("只能在群聊使用呢~")
        return
    }
    
    const groupId = e.group_id
	const userId = e.user_id
	let data = await loadfile(groupId)
	    data = data[groupId]

	if (!data.fuck && !e.isMaster) {
        logger.mark(`${groupId}还未开启银趴！`)
        return
    }
	
    // 防止给自己
    if (e.at === userId) {
        await e.reply([segment.at(userId), ` 哎呀！你要🌿你自己？办不到，怎么想都办不到吧！`], false, { recallMsg: 20 })
        return
    }
	
    if (!e.isMaster) {
        const toudown = toudowns[userId]
        if (toudown && toudown > Date.now()) {
            const remainingTime = toudown - Date.now()
            const minutes = Math.floor(remainingTime / 60000)
            const seconds = Math.ceil((remainingTime % 60000) / 1000)
            let timeString = `${minutes > 0 ? `${minutes}分` : ''}${seconds}秒`
            await e.reply([segment.at(userId), ` 你已经榨不出来任何东西了, 请先休息 ${timeString}~`], false, { recallMsg: 20 })
            return
        }
    }
    let key = e.msg.replace(/#|透群友/g, "").trim()
	
    logger.mark("用户命令：", e.msg)
	const num = Math.floor(Math.random() * 100)
    if (e.at || key) {
		let qq = ''
		if (/^\d+$/.test(key)) {
	    	qq = key
	    }
	    else if (e.at) {
		    qq = e.at
	    } 
		let mem
        try {
		    mem = await e.group.pickMember(qq).getInfo()
		} catch(error) {
			await e.reply(`❎请输入正确的qq号`, true, { recallMsg: 20 })
			return
		}
		toudowns[userId] = Date.now() + data.cd * 1000
        const name = mem.card || mem.nickname

        await e.reply(`现在咱将把 ${name} 送给 ${e.sender.card || e.sender.nickname} 涩涩！`, false, { recallMsg: 20 })
        await common.sleep(3000)

        // 随机事件
        if (num <= min) {
            await e.reply(`${e.sender.card || e.sender.nickname} 成功逮到了亲🐶的爱群友 ${name} 结果给🌿歪🐍外面了，只因不行，好可惜呢~`, false, { recallMsg: 20 })
        } else {
            await this.handleInjection(e, qq, name, e.sender.card || e.sender.nickname)
        }
    } else {
        await e.reply(`现在咱将随机抽取一位幸运裙友送给 ${e.sender.card || e.sender.nickname} 涩涩！`, false, { recallMsg: 20 })
        await common.sleep(3000)

        const map = await e.group.getMemberMap()
        const arrMember = Array.from(map.values())
        let mem
        do {
            mem = arrMember[Math.round(Math.random() * (arrMember.length - 1))]
        } while (mem.user_id === userId)

        if (num <= min) {
            await e.reply(`${e.sender.card || e.sender.nickname} 成功逮到了亲🐶的爱群友 ${mem.card || mem.nickname} 结果给🌿歪🐍外面了，只因不行，好可惜呢~`, false, { recallMsg: 20 })
        } else {
            await this.handleInjection(e, mem.user_id, mem.nickname, e.sender.card || e.sender.nickname)
        }
    }
  }
  
  
  async fuckowner(e) {
    if (!e.isGroup) {
        await e.reply("只能在群聊使用呢~")
        return
    }

    const groupId = e.group_id
	const userId = e.user_id
	let data = await loadfile(groupId)
	    data = data[groupId]

	if (!data.fuck && !e.isMaster) {
        logger.mark(`${groupId}还未开启银趴！`)
        return
    }

    if (!e.isMaster) {
        const toudown = toudowns[userId]
        if (toudown && toudown > Date.now()) {
            const remainingTime = toudown - Date.now()
            const minutes = Math.floor(remainingTime / 60000)
            const seconds = Math.ceil((remainingTime % 60000) / 1000)
            let timeString = `${minutes > 0 ? `${minutes}分` : ''}${seconds}秒`
            await e.reply([segment.at(userId), ` 你已经榨不出来任何东西了, 请先休息 ${timeString}~`], false, { recallMsg: 20 })
            return
        }
        toudowns[userId] = Date.now() + data.cd * 1000
    }

    logger.mark("用户命令：", e.msg)

    // 检查是否是群主
    if (e.group.pickMember(userId).is_owner) {
        await e.reply([segment.at(userId), " 尊🐶的贵群主，你要🌿你自己？"], false, { recallMsg: 20 })
        return
    }

    const map = await e.group.getMemberMap()
    const arrMember = Array.from(map.values())
    let mem = arrMember[Math.floor(Math.random() * arrMember.length)]
    logger.info(mem)
    while (true) {
        if (e.group.pickMember(mem.user_id).is_owner) {
            await e.reply(`现在咱将把群主 ${mem.card || mem.nickname} 送给 ${e.sender.card || e.sender.nickname} 涩涩！`, false, { recallMsg: 20 })
            await common.sleep(3000)
            // 随机事件
            const num = Math.floor(Math.random() * 100)
            if (num <= min) {
                await e.reply(`${e.sender.card || e.sender.nickname} 成功逮到了尊🐶的贵群主 ${mem.card || mem.nickname} 结果给🌿歪🐍外面了，只因不行，好可惜呢~`, false, { recallMsg: 20 })
            } else {
                await this.handleInjection(e, mem.user_id, mem.card || mem.nickname, e.sender.card || e.sender.nickname)
            }
            break
        } else {
            mem = arrMember[Math.floor(Math.random() * arrMember.length)]
        }
    }
  }


  async fuckadmin(e) {
    if (!e.isGroup) {
        await e.reply("只能在群聊使用呢~")
        return
    }

    const groupId = e.group_id
	const userId = e.user_id
	let data = await loadfile(groupId)
	    data = data[groupId]

	if (!data.fuck && !e.isMaster) {
        logger.mark(`${groupId}还未开启银趴！`)
        return
    }

    if (!e.isMaster) {
        const toudown = toudowns[userId]
        if (toudown && toudown > Date.now()) {
            const remainingTime = toudown - Date.now()
            const minutes = Math.floor(remainingTime / 60000)
            const seconds = Math.ceil((remainingTime % 60000) / 1000)
            const timeString = `${minutes > 0 ? `${minutes}分` : ""}${seconds}秒`
            await e.reply([segment.at(userId), ` 你已经榨不出来任何东西了, 请先休息 ${timeString}~`], false, { recallMsg: 20 })
            return
        }
        toudowns[userId] = Date.now() + data.cd * 1000
    }

    logger.mark("用户命令：", e.msg)

    const map = await e.group.getMemberMap()
    const arrMember = Array.from(map.values())
    let mem
    do {
        mem = arrMember[Math.round(Math.random() * (arrMember.length - 1))]
    } while (mem.user_id === userId)

    // 查找群管理员
    while (true) {
        if (e.group.pickMember(mem.user_id).is_admin) {
            await e.reply(`现在咱将把管理 ${mem.card || mem.nickname} 送给 ${e.sender.card || e.sender.nickname} 涩涩！`, false, { recallMsg: 20 })
            await common.sleep(3000)
			const num = Math.floor(Math.random() * 100)
            if (num <= min) {
                await e.reply(`${e.sender.card || e.sender.nickname} 成功逮到了亲🐶的爱管理 ${mem.card || mem.nickname} 结果给🌿歪🐍外面了，只因不行，好可惜呢~`, false, { recallMsg: 20 })
            } else {
                await this.handleInjection(e, mem.user_id, mem.card || mem.nickname, e.sender.card || e.sender.nickname)
            }
            break
        } else {
            mem = arrMember[Math.round(Math.random() * (arrMember.length - 1))]
        }
    }
  }


  async toucha(e) {
    if (!e.isGroup) {
        await e.reply("只能在群聊使用呢~")
        return
    }
    let key = e.msg.replace(/#|(挨透|被透|注射|注入|被草|银趴)查询/g, "").trim()
	let qq = ''
	if (/^\d+$/.test(key)) {
		qq = key
	}
	else if (e.at) {
		qq = e.at
	} 
	else {
		qq = e.user_id
	}
    
    let dirname = `${fuckpath}/${e.group_id}`
    if (!fs.existsSync(dirname)) {
	    await e.reply(`[${e.group_id}] 还没有银趴记录！`)
        return
    }
    let mem
    try {
		mem = await e.group.pickMember(qq).getInfo()
    } catch(error) {
		await e.reply(`❎请输入正确的qq号`, true, { recallMsg: 10 })
		return
	}
	
    const wen = `${dirname}/${qq}.json` 
    if (!fs.existsSync(wen)) {
        const replyMsg = (e.at || key) ? 'ta今天还没有被透过！' : '你今天还没有被透过！'
        await e.reply(replyMsg)
        return
    }

    const content = JSON.parse(fs.readFileSync(wen, 'utf8'))

    let shuju = []

    // 将 userId 按照 content[userId].num 从大到小排序
    let sortedUserIds = Object.keys(content)
        .filter(userId => /^\d+$/.test(userId))
        .sort((a, b) => content[b].num - content[a].num)
		.slice(0, 100)
		
    let n = 1
    for (const userId of sortedUserIds) {
        if (content[userId]) {
            const member = await e.group.pickMember(userId).getInfo()
            const name = member.card || member.nickname
            let avatar = `${avatorurl}${userId}&s=0`
            shuju.push({
                n: `「${n}」`,
                avator: avatar,
                name: name,
                content: `${content[userId].num} mL`,
                con: `${content[userId].cs} 次`
            })
            n++
        }
    }

    const title = `${mem.card || mem.nickname} 今日被透详情`
	let [date, nm] = await loaddata(e, qq)

    const data1 = {
        tplFile: './resources/html/fuck/list.html',
        imgType: 'jpeg',
        htmlDir: ml,
        shuju,
        title,
        date: `${nm} 次，${date} mL`
    }

    // 生成截图并发送
    const img = await puppeteer.screenshot("temp", data1)
    await e.reply(img)

    return true
}


 async toubang(e) {
    if (!e.isGroup) {
        await e.reply("只能在群聊使用呢~")
        return
    }

    let groupId = e.group_id // 获取群聊号
	let dirname = `${fuckpath}/${groupId}`
    if (!fs.existsSync(dirname)) {
        await e.reply('本群今天还没有人被透过！')
        return
    }
	
	const txtFiles = fs.readdirSync(dirname).filter(file => path.extname(file) === '.json')
    if (txtFiles.length === 0) {
        await e.reply('本群今天还没有人被透过！')
        return
    }
    
    let shuju = []

    // 读取并排序数据
    const res = await Promise.all(txtFiles.map(async (file) => {
        const qq = path.basename(file, '.json')
		let [date, n] = await loaddata(e, qq)
        try {
            const mem = await e.group.pickMember(qq).getInfo()
            const name = mem.card || mem.nickname
            return {
                qq,
                content: date,
                con: n,
                name
            }
        } catch (error) {
            return null // 无法找到成员的情况
        }
    }))
    
    // 过滤掉 null 数据并排序
    const filteredRes = res.filter(item => item !== null).sort((a, b) => b.content - a.content)

    // 准备排行榜数据
    filteredRes.slice(0, 100).forEach(({ qq, content, con, name }, index) => {
        const avatar = `${avatorurl}${qq}&s=0`
        shuju.push({
            n: `「${index + 1}」`,
            avator: avatar,
            name: name,
            content: `${content} mL`,
            con: `${con} 次`
        })
    })

    const title = `本群今日被透排行榜`
    const data1 = {
        tplFile: './resources/html/fuck/list.html',
        imgType: 'jpeg',
        htmlDir: ml,
        shuju,
        title
    }

    // 生成截图并发送
    const img = await puppeteer.screenshot("temp", data1)
    await e.reply(img)

    return true
  }
  
  // 处理注入逻辑
  async handleInjection(e, targetId, targetName, senderName) {
    const jb = Math.random() * 100

	let groupId = e.group_id // 获取群聊号
	let dirname = `${fuckpath}/${groupId}`
	if (!fs.existsSync(dirname)) {
        await fs.mkdirSync(dirname)
    }
    
	let path = `${dirname}/${targetId}.json`
    if (!fs.existsSync(path)) {
        await fs.writeFileSync(path, `{}`)
        logger.mark(`${targetId}数据文件不存在自动创建`)
    }
    
	let userdata = JSON.parse(fs.readFileSync(path, 'utf8'))
    if (!userdata[e.user_id]) {
		userdata[e.user_id] = { num: 0, cs: 0}
	}
    
	let znum
    if (jb > 60) {
        znum = Math.random() * (30 - 10) + 30
    } else {
        znum = (Math.random() * 20)
    }
	znum = znum.toFixed(2)
	
	//数值累加
	let aa = userdata[e.user_id].num + +znum
	    aa = aa.toFixed(2)
	
	//更新数值	
	userdata[e.user_id].num = Number(aa)
    userdata[e.user_id].cs ++
	
    // 更新文件
	let txt = JSON.stringify(userdata, null, 2)
    await fs.writeFileSync(path,txt) 
    
    // 回复
	let name
	if (e.msg.includes('群主')) {
		name = '尊🐶的贵群主'
	} else if (e.msg.includes('管理')) {
		name = '亲🐶的爱管理'
    } else {
		name = '亲🐶的爱群友'
    }
	
	let [date, n] = await loaddata(e, targetId)
	 
    await e.reply([
        `好欸！${senderName} ${jb > 60 ? '✨触发暴击✨，狠狠地给' : '成功给'}${name} ${targetName} 注入了 ${znum}mL 的脱氧核糖核酸~\nta今日被透${n}次，总计${date} mL `,
        segment.image(`${avatorurl}${targetId}`)
    ])
	
	return true
  }

}

async function loadfile(id) {
	let data = YAML.parse(fs.readFileSync(file, 'utf8'))
	if (!data[id]) {
	    data[id] = { fuck: false, cd: 300 }
	}
	return data
}

async function loaddata(e, id) {
	let data = JSON.parse(fs.readFileSync(`${fuckpath}/${e.group_id}/${id}.json`, 'utf8'))
    let date = 0
	let n = 0
    for (let i in data) {
		date += data[i].num
		n += data[i].cs
	}
	return [date.toFixed(2), n]
}


const job = schedule.scheduleJob('0 0 0 * * *', function() {
    const files = fs.readdirSync(fuckpath)
    let deletedCount = 0 
    for (let sj of files) {
		let fl = `${fuckpath}/${sj}`
		if (!fs.statSync(fl).isDirectory()) continue
		const fullpath = fs.readdirSync(fl).filter(file => path.extname(file) === '.json')
		for (let k of fullpath) {
            fs.unlinkSync(`${fl}/${k}`)
            deletedCount++ 
		}
		fs.rmdirSync(fl)
    }
	let msg = `清空当日银趴数据：删除文件数量 ${deletedCount} `
	logger.info(msg)
});



